<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/7/21
 * Time: 下午3:10
 */
namespace PddWechat\Models\PddWechat\Service;

use Dai\Framework\Base\BaseService;
use Dai\Framework\Library\Log;
use PddWechat\Library\WechatLibrary;

class JsConfig extends BaseService {

    private $str = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";

    public function execute($basePageInfo) {
        /** @var \PddWechat\Models\PddWechat\Param\JsConfigParam $params */
        $params = $basePageInfo->params;

        if(intval(strrpos($params->url,'#')) > 0) {
            $url = substr($params->url,0,strrpos($params->url,'#'));
        } else {
            $url = $params->url;
        }
        $timestamp = time();
        $jsapi_ticket = WechatLibrary::getWechatJsToken();
        $noncestr = $this->createRandomStr();
        $signature = $this->bulidSignature($jsapi_ticket,$noncestr,$timestamp,$url);
        $result  = [
            'jsapi_ticket' => $jsapi_ticket,
            'noncestr' => $noncestr,
            'timestamp' => $timestamp,
            'url' => $url,
            'signature' => $signature,
        ];
        Log::writeLog("INFO",json_encode($result));
        return $result;
    }

    private function bulidSignature($jsapi_ticket,$noncestr,$timestamp,$url)
    {
        $array = [$jsapi_ticket,$noncestr,$timestamp,$url];
        sort($array);
        $tmpstr = implode('',$array);
        $signature = sha1($tmpstr);
        return $signature;
    }

    private function createRandomStr()
    {
        str_shuffle($this->str);
        $randomStr = substr(str_shuffle($this->str),26,16);
        return $randomStr;
    }
}